package com.jingdun.sport.files

import com.jingdun.sport.bean.model.ApiResult
import com.jingdun.sport.common.bean.Qiniu
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.multipart.MultipartFile
import java.net.URI

@RestController
@RequestMapping("/file")
class UploadController {
    @Autowired
    private lateinit var attachFileService: AttachFileServiceImpl

    @Autowired
    private lateinit var qiniu: Qiniu

    @PostMapping("/upload")
    fun uploadElementFile(@RequestParam("file") file: MultipartFile): ResponseEntity<Any> {
        val apiResult: ApiResult<*> = ApiResult<Any?>()
        if (file.isEmpty) {
            //return ResponseEntity.noContent().build()
            apiResult.code = HttpStatus.NO_CONTENT.value()
            apiResult.msg = HttpStatus.NO_CONTENT.reasonPhrase
            return ResponseEntity.ok(apiResult)
        }
        val fileName: String = attachFileService.uploadFile(file.bytes, file.originalFilename)
        val fileUrl = qiniu.pathToUrl(fileName)
        //return ResponseEntity.created(URI(fileUrl)).body(fileUrl)
        apiResult.msg = fileUrl
        apiResult.data = fileUrl
        return ResponseEntity.ok(apiResult)
    }
}